import {useEffect, useState} from 'react'
import {View} from '@tarojs/components'
import {AtButton, AtRadio} from "taro-ui";
import Taro from "@tarojs/taro";
import "taro-ui/dist/style/components/button.scss" // 按需引入
import './index.scss'
import GlobalFooter from "../../components/GlobalFooter";
import './../index/index.scss'
import questions from '../../data/questions.json';

export default () => {
  //当前题目号
  const [questionCount, setQuestionCount] = useState<number>(1);
  //当前题目
  const [question, setQuestion] = useState(questions[0]);
  //当前题目选项
  const questionOptions = question.options.map((option) => {
    return {label: `${option.key}: ${option.value}`, value: option.key};
  })
  // 当前回答
  const [currentAnswer, setCurrentAnswer] = useState<string>();
  //回答列表
  const [questionResultList] = useState<string[]>([]);

  //题目被切换时的动作
  useEffect(() => {
    setQuestion(questions[questionCount - 1])
    setCurrentAnswer(questionResultList[questionCount - 1])
  }, [questionCount])

  //跳转函数
  const toResult:()=>void = () => {
    Taro.redirectTo({
      url: `/pages/result/index`,
    })
  }

  return (
    <View className='answer'>
      <text className='topic'>
        {questionCount+": "+question.title}
      </text>

      <AtRadio className='options' options={questionOptions} value={currentAnswer} onClick={(value) => {
                //选中后改变CurrentAnswer的值
                 setCurrentAnswer(value)
                 // 记录回答
                questionResultList[questionCount - 1] = value;
               }}
      />
      {/*下一题按钮*/}
      {
        questionCount != questions.length && <AtButton
          type='primary'
          className=' at-button--primary entryButton'
          size="normal"
          circle
          disabled={!currentAnswer}
          onClick={() => {
            setQuestionCount(questionCount + 1)
          }}
        >
          下一题
        </AtButton>
      }
      {/*查看结果按钮*/}
      {questionCount == questions.length &&
        <AtButton
          type='primary'
          className='at-button--primary entryButton'
          size="normal"
          disabled={!currentAnswer}
          circle
          onClick={()=>{
            Taro.setStorageSync("questionResultList", questionResultList)
            toResult()
          }}

        >
          查看结果
        </AtButton>}
      {/*上一题按钮*/}
      {questionCount != 0 &&
        <AtButton
          type='primary'
          className='at-button--primary entryButton nextButton'
          size="normal"
          circle
          onClick={() => {
            setQuestionCount(questionCount - 1)
          }}
        >
          上一题
        </AtButton>}
      <GlobalFooter></GlobalFooter>

    </View>
  )
}
